const categoryDao = require("@/dao/category");
const z_base_Dao = require("@/dao/z_base");
const CategoryModal = require("@/model/Category");
const ArticleModal = require("@/model/Article");
const { cloneDeep } = require("lodash");
const { ErrorCode } = require("@/utils/r/code");

const Category = {
  GetOption() {
    return new Promise((resolve, reject) => {
      try {
        resolve(categoryDao.GetOption());
      } catch (error) {
        reject(error);
      }
    });
  },
  async GetList(query) {
    const { datas, total } = await categoryDao.GetList(query);
    return {
      total,
      pageData: datas,
      pageSize: +query.page_size,
      pageNum: +query.page_num,
    };
  },
  async SaveOrUpdate(body) {
    //创建前端不传递id，更新前端传递id
    const exist = await z_base_Dao.GetOne(CategoryModal.CategoryVo, {
      name: body.name,
    });

    if (exist && body?.id !== exist?.id) {
      //代表新插入的标签已经存在
      return ErrorCode.ERROR_TAG_EXIST;
    }
    const category = cloneDeep(body);
    category.updated_at = new Date().toLocaleString();
    if (body?.id) {
      //更新
      await z_base_Dao.Update(CategoryModal.CategoryVo, category, {
        id: body.id,
      });
    } else {
      //创建
      category.created_at = new Date().toLocaleString();
      await z_base_Dao.Create(CategoryModal.CategoryVo, category);
    }

    return ErrorCode.OK;
  },
  async Delete(ids) {
    //删除一个标签，首先需要判断该标签是否用于文章列表中
    const total = await z_base_Dao.Count(
      ArticleModal.Article,
      "category_id in (:ids)", //方便处理ids为数组的情况
      ids
    );
    if (total > 0) {
      //代表要删除的标签被文章使用，不能删除
      return ErrorCode.ERROR_TAG_ART_EXIST;
    }
    await z_base_Dao.Delete(CategoryModal.CategoryVo, { id: ids });
    return ErrorCode.OK;
  },
  async GetFrontList() {
    const { datas } = await categoryDao.GetList();
    return {
      list: datas,
      total: datas.length,
    };
  },
};

module.exports = Category;
